import time

from flask import request
from funcy import project

from redash import models
from redash.serializers import serialize_alert
from redash.handlers.base import BaseResource, get_object_or_404, require_fields
from redash.permissions import (
    require_access,
    require_admin_or_owner,
    require_permission,
    view_only,
)
from redash.utils import json_dumps


class AlertResource(BaseResource):
    def get(self, alert_id):
        alert = get_object_or_404(
            models.Alert.get_by_id_and_org, alert_id, self.current_org
        )
        require_access(alert, self.current_user, view_only)
        self.record_event(
            {"action": "view", "object_id": alert.id, "object_type": "alert"}
        )
        return serialize_alert(alert)

    def post(self, alert_id):
        req = request.get_json(True)
        params = project(req, ("options", "name", "query_id", "rearm"))
        alert = get_object_or_404(
            models.Alert.get_by_id_and_org, alert_id, self.current_org
        )
        require_admin_or_owner(alert.user.id)

        self.update_model(alert, params)
        models.db.session.commit()

        self.record_event(
            {"action": "edit", "object_id": alert.id, "object_type": "alert"}
        )

        return serialize_alert(alert)

    def delete(self, alert_id):
        strsql = """delete From alert_subscriptions where alert_id="""+str(alert_id)+""" and user_id="""+str(self.current_user.id)+""";
            delete From alerts where id="""+str(alert_id)+""" 
            and id not in(select alert_id from alert_subscriptions where alert_id="""+str(alert_id)+""" and user_id !="""+str(self.current_user.id)+""");"""
        models.db.session.execute(strsql)
        models.db.session.commit()
        # alert = get_object_or_404(
        #     models.Alert.get_by_id_and_org, alert_id, self.current_org
        # )
        # require_admin_or_owner(alert.user_id)
        # models.db.session.delete(alert)
        # models.db.session.commit()


class AlertMuteResource(BaseResource):
    def post(self, alert_id):
        alert = get_object_or_404(
            models.Alert.get_by_id_and_org, alert_id, self.current_org
        )
        require_admin_or_owner(alert.user.id)

        alert.options["muted"] = True
        models.db.session.commit()

        self.record_event(
            {"action": "mute", "object_id": alert.id, "object_type": "alert"}
        )

    def delete(self, alert_id):
        alert = get_object_or_404(
            models.Alert.get_by_id_and_org, alert_id, self.current_org
        )
        require_admin_or_owner(alert.user.id)

        alert.options["muted"] = False
        models.db.session.commit()

        self.record_event(
            {"action": "unmute", "object_id": alert.id, "object_type": "alert"}
        )


class AlertListResource(BaseResource):
    # def post(self):
    #     req = request.get_json(True)
    #     require_fields(req, ("options", "name", "query_id"))

    #     query = models.Query.get_by_id_and_org(req["query_id"], self.current_org)
    #     require_access(query, self.current_user, view_only)

    #     alert = models.Alert(
    #         name=req["name"],
    #         query_rel=query,
    #         user=self.current_user,
    #         rearm=req.get("rearm"),
    #         options=req["options"],
    #     )

    #     models.db.session.add(alert)
    #     models.db.session.flush()
    #     models.db.session.commit()

    #     self.record_event(
    #         {"action": "create", "object_id": alert.id, "object_type": "alert"}
    #     )

    #     return serialize_alert(alert)

    def post(self):
        req = request.get_json(force=True)
        page = req["page"]if "page" in req else 1
        page_size = req["pagesize"] if "pagesize" in req else 20
        isread = str(req["isread"]) if "isread" in req else "0"
        name = str(req["name"]) if "name" in req else ""
        orderfield = req["orderfield"] if "orderfield" in req else "updated_atformat"
        order = req["order"] if "order" in req else 1
        if orderfield=="name":
            orderfield ="t1.name"
        elif orderfield=="updated_atformat":
            orderfield ="t1.updated_at"
        else:
            orderfield ="t1.updated_at"        

        strwhere ="t2.user_id=" +str(self.current_user.id)
        if isread =="1" :
            strwhere = strwhere + " and t2.isread = false"
        elif isread =="2" :
            strwhere = strwhere + " and t2.isread = true"
        if name !='' :
            strwhere = strwhere + " and t1.name like '%"+name+"%'"

        strgetfield =""" t1.*,t2.isread,to_char(t1.updated_at,'YYYY-MM-DD') updated_atformat,case when t2.isread then '已读' else '未读' end strisread,
         t3.name as username """

        tblname = """ public.alerts t1 inner join public.alert_subscriptions t2 on t1.id=t2.alert_id
          inner join public.users t3 on t1.user_id=t3.id """

        result = models.ContractApply.get_pagequery(tblname,strgetfield,orderfield,page_size,page,order,strwhere)
        return result[0]

        # self.record_event({"action": "list", "object_type": "alert"})
        # return [
        #     serialize_alert(alert)
        #     for alert in models.Alert.all(group_ids=self.current_user.group_ids)
        # ]

class AlertNoreadResource(BaseResource):
    def get(self):
        sql = "select count(*) from alert_subscriptions where alert_subscriptions.user_id="+str(self.current_user.id)+" and alert_subscriptions.isread=false"
        rows = models.db.session.execute(sql).fetchall()
        return {"data": rows[0][0]}
        

class AlertReadResource(BaseResource):
    def get(self, alert_id,type):
        if type == "read":
            strsql = """update alert_subscriptions set isread=case when isread then false else true end 
            where alert_subscriptions.alert_id in (""" + str(alert_id) + """) and alert_subscriptions.user_id = '"""+str(self.current_user.id)+"'"
        else :
            strsql = """delete From alert_subscriptions where alert_id in (""" + str(alert_id) + """) and user_id="""+str(self.current_user.id)+""";
            delete From alerts where id in (""" + str(alert_id) + """)
            and id not in(select alert_id from alert_subscriptions where alert_id in (""" + str(alert_id) + """) and user_id !="""+str(self.current_user.id)+""");"""
        models.db.session.execute(strsql)
        models.db.session.commit()

class AlertSubscriptionListResource(BaseResource):
    def post(self, alert_id):
        req = request.get_json(True)

        alert = models.Alert.get_by_id_and_org(alert_id, self.current_org)
        require_access(alert, self.current_user, view_only)
        kwargs = {"alert": alert, "user": self.current_user}

        if "destination_id" in req:
            destination = models.NotificationDestination.get_by_id_and_org(
                req["destination_id"], self.current_org
            )
            kwargs["destination"] = destination

        subscription = models.AlertSubscription(**kwargs)
        models.db.session.add(subscription)
        models.db.session.commit()

        self.record_event(
            {
                "action": "subscribe",
                "object_id": alert_id,
                "object_type": "alert",
                "destination": req.get("destination_id"),
            }
        )

        d = subscription.to_dict()
        return d

    def get(self, alert_id):
        alert = models.Alert.get_by_id_and_org(alert_id, self.current_org)
        require_access(alert, self.current_user, view_only)

        subscriptions = models.AlertSubscription.all(alert_id)
        return [s.to_dict() for s in subscriptions]


class AlertSubscriptionResource(BaseResource):
    def delete(self, alert_id, subscriber_id):
        subscription = models.AlertSubscription.query.get_or_404(subscriber_id)
        require_admin_or_owner(subscription.user.id)
        models.db.session.delete(subscription)
        models.db.session.commit()

        self.record_event(
            {"action": "unsubscribe", "object_id": alert_id, "object_type": "alert"}
        )
